<template>
  <div class="editupload">
    <van-nav-bar left-arrow title="头像上传">
      <template #left>
        <i
          class="iconfont iconbtn_nav_back iconFont"
          @click="$router.go(-1)"
        ></i>
      </template>
      <template #right>
        <span v-if="isSave" @click="save">保存</span>
      </template>
    </van-nav-bar>
    <div class="main">
      <van-uploader
        v-model="fileList"
        :max-count="1"
        preview-size="200"
        :after-read="afterRead"
      />
    </div>
  </div>
</template>

<script>
import { apiUpload, apiEditInfo } from '@/api/au.js'
export default {
  data () {
    return {
      isSave: false,
      fileList: [{ url: this.$store.state.userInfo.avatar }],
      imgId: 0
    }
  },
  methods: {
    // 上传功能
    async afterRead (file) {
      //    console.log(file)
      file.status = 'uploading'
      file.message = '上传中'
      const res = await apiUpload(file.file)
      // console.log(res)
      this.imgId = res.data[0].id
      this.isSave = true
      file.status = 'done'
    },
    // 保存
    async save () {
      await apiEditInfo({
        avatar: this.imgId
      })
      this.$store.dispatch('setUserInfo')
      this.$toast.success('头像修改成功')
      this.$router.push('/info')
    }
  }
}
</script>

<style lang="less">
.editupload {
  font-size: 12px;
  .iconFont {
    font-size: 44px;
  }
  .van-nav-bar__left {
    padding-left: 0;
  }
  .main {
    text-align: center;
  }
}
</style>
